class SectorsController < ApplicationController
  layout "master"

  # GET /sectors
  # GET /sectors.xml
  def index
    @sectors = Sector.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @sectors }
    end
  end

  # GET /sectors/1
  # GET /sectors/1.xml
  def show
    @sector = Sector.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @sector }
    end
  end

  # GET /sectors/new
  # GET /sectors/new.xml
  def new
    @sector = Sector.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @sector }
    end
  end

  # GET /sectors/1/edit
  def edit
    @sector = Sector.find(params[:id])
  end

  # POST /sectors
  # POST /sectors.xml
  def create
    @sector = Sector.new(params[:sector])    

    respond_to do |format|
      if @sector.save
        format.html { redirect_to(@sector, :notice => 'Sector was successfully created.') }
        format.xml  { render :xml => @sector, :status => :created, :location => @sector }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @sector.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /sectors/1
  # PUT /sectors/1.xml
  def update
    @sector = Sector.find(params[:id])

    respond_to do |format|
      if @sector.update_attributes(params[:sector])
        format.html { redirect_to(@sector, :notice => 'Sector was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @sector.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /sectors/1
  # DELETE /sectors/1.xml
  def destroy
    @sector = Sector.find(params[:id])
    @sector.destroy

    respond_to do |format|
      format.html { redirect_to(sectors_url) }
      format.xml  { head :ok }
    end
  end

  def upload
    sector = Sector.find(params[:document][:sector_id])
    icon = params[:document] ? params[:document][:icon] : nil
    image = params[:document] ? params[:document][:image] : nil
    
    if icon
      if sector.icon
        document = sector.icon
        document.destroy
      end
      sector.icon = Document.new
      sector.icon.document_file=icon
    end

    if image
      if sector.image
        document = sector.image
        document.destroy
      end
      sector.image = Document.new
      sector.image.document_file=image
    end

    sector.save
    redirect_to url_for :controller => :sectors, :action => :edit, :id => sector.id
  end
end
